package com.sky.controller.user;

import com.alibaba.fastjson.JSONArray;
import com.sky.entity.Category;
import com.sky.result.Result;
import com.sky.service.CategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController("userCategoryController")
@RequestMapping("/user/category")
@Api(tags = "C端-分类接口")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 查询分类
     *
     * @param type
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("查询分类")
    public Result<List<Category>> list(Integer type) {
        //1. 创建redis中的key
        String key = "category_" + type;

        //2. 获取redis的分类
        String category = stringRedisTemplate.opsForValue().get(key);
        List<Category> categoryList = JSONArray.parseArray(category, Category.class);

        //3. 判断如果存在则返回
        if (categoryList != null) {
            return Result.success(categoryList);
        }
        //4. 不存在就走mysql
        categoryList = categoryService.list(type);

        //5. 在缓存到redis中的key
        stringRedisTemplate.opsForValue().set(key, JSONArray.toJSONString(categoryList));
        return Result.success(categoryList);

    }
}
